<template>
  <div class="profile-container">
    <el-row :gutter="20">
      <el-col :span="8">
        <el-card class="user-info-card">
          <template #header>
            <div class="card-header">
              <span>个人信息</span>
              <el-button type="text" @click="editMode = !editMode">
                {{ editMode ? '取消' : '编辑' }}
              </el-button>
            </div>
          </template>
          <el-form :model="userForm" :disabled="!editMode" label-width="80px">
            <el-form-item label="用户名">
              <el-input v-model="userForm.username" :disabled="true" />
            </el-form-item>
            <el-form-item label="邮箱">
              <el-input v-model="userForm.email" />
            </el-form-item>
            <el-form-item v-if="editMode">
              <el-button type="primary" @click="updateProfile" :loading="updating">
                保存修改
              </el-button>
            </el-form-item>
          </el-form>
        </el-card>
      </el-col>

      <el-col :span="16">
        <el-card class="vote-history-card">
          <template #header>
            <div class="card-header">
              <span>投票历史</span>
            </div>
          </template>
          
          <el-table :data="voteHistory" style="width: 100%">
            <el-table-column prop="voteTopic.title" label="投票主题" />
            <el-table-column prop="voteOption.content" label="投票选项" />
            <el-table-column prop="votedAt" label="投票时间">
              <template #default="scope">
                {{ formatDate(scope.row.votedAt) }}
              </template>
            </el-table-column>
            <el-table-column label="操作">
              <template #default="scope">
                <el-button 
                  type="text" 
                  @click="viewVoteDetail(scope.row.voteTopic.id)"
                >
                  查看详情
                </el-button>
              </template>
            </el-table-column>
          </el-table>

          <div class="pagination">
            <el-pagination
              v-model:current-page="currentPage"
              v-model:page-size="pageSize"
              :total="total"
              :page-sizes="[10, 20, 30, 50]"
              layout="total, sizes, prev, pager, next"
              @size-change="handleSizeChange"
              @current-change="handleCurrentChange"
            />
          </div>
        </el-card>
      </el-col>
    </el-row>
  </div>
</template>

<script>
import { ref, reactive, onMounted } from 'vue'
import { useStore } from 'vuex'
import { useRouter } from 'vue-router'
import { ElMessage } from 'element-plus'
import dayjs from 'dayjs'

export default {
  name: 'UserProfile',
  setup() {
    const store = useStore()
    const router = useRouter()
    const editMode = ref(false)
    const updating = ref(false)
    const currentPage = ref(1)
    const pageSize = ref(10)
    const total = ref(0)
    const voteHistory = ref([])

    const userForm = reactive({
      username: '',
      email: ''
    })

    const loadUserProfile = async () => {
      try {
        const response = await store.dispatch('fetchUserProfile')
        const { username, email } = response.data
        userForm.username = username
        userForm.email = email
      } catch (error) {
        ElMessage.error('获取用户信息失败')
      }
    }

    const loadVoteHistory = async () => {
      try {
        const response = await store.dispatch('fetchVoteHistory', {
          page: currentPage.value,
          size: pageSize.value
        })
        voteHistory.value = response.data.content
        total.value = response.data.total
      } catch (error) {
        ElMessage.error('获取投票历史失败')
      }
    }

    const updateProfile = async () => {
      try {
        updating.value = true
        await store.dispatch('updateProfile', userForm)
        ElMessage.success('更新成功')
        editMode.value = false
      } catch (error) {
        ElMessage.error('更新失败')
      } finally {
        updating.value = false
      }
    }

    const viewVoteDetail = (voteId) => {
      router.push(`/votes/${voteId}`)
    }

    const handleSizeChange = (val) => {
      pageSize.value = val
      loadVoteHistory()
    }

    const handleCurrentChange = (val) => {
      currentPage.value = val
      loadVoteHistory()
    }

    const formatDate = (date) => {
      return dayjs(date).format('YYYY-MM-DD HH:mm')
    }

    onMounted(() => {
      loadUserProfile()
      loadVoteHistory()
    })

    return {
      editMode,
      updating,
      userForm,
      voteHistory,
      currentPage,
      pageSize,
      total,
      updateProfile,
      viewVoteDetail,
      handleSizeChange,
      handleCurrentChange,
      formatDate
    }
  }
}
</script>

<style scoped>
.profile-container {
  padding: 20px;
  max-width: 1200px;
  margin: 0 auto;
}

.card-header {
  display: flex;
  justify-content: space-between;
  align-items: center;
}

.user-info-card {
  margin-bottom: 20px;
}

.vote-history-card {
  margin-bottom: 20px;
}

.pagination {
  margin-top: 20px;
  display: flex;
  justify-content: center;
}
</style>
